<?php

//module/Authentication/src/Authentication/Controller/PasswdController.php
namespace Authentication\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\View\Model\ViewModel;

use Authentication\Model\Passwd;

use Zend\Mail\Message;
//use Zend\Mail\Transport\Sendmail as SendmailTransport;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;

class PasswdController extends AbstractActionController
{

   protected $form;
   protected $usuarioTable;

   private function getForm() {
      if (! $this->form) {
         $passwd     = new Passwd();
         $builder    = new AnnotationBuilder();
         $this->form = $builder->createForm($passwd);
      }

      return $this->form;
   }

   public function indexAction() {
      $form = $this->getForm();
      $form->get('submit')->setAttribute('value', 'RECUPERAR');

      return array(
          'form'      => $form
      );
   }

   private function generateRandomPassword() {
      return \base_convert(\uniqid('pass', true), 10, 36);
   }

   private function sendPassword($usuario) {

      $usuario->password = $this->generateRandomPassword();

      $message = new Message();
      $message->addTo($usuario->mail)
              ->addFrom('asistencia.uca.edu.py@gmail.com')
              ->setSubject('Recuperación de Contraseña')
              ->setBody("Universidad Católica / Sistema Asistencia \n\n" .
                        "Solicitud de restauración de contraseña para: " .
                        $usuario->apellido . "," . $usuario->nombre . "\n" .
                        "Su nueva Contraseña es: " . $usuario->password . "\n\n" .
                        "Atte.");

      //$transport = new SendmailTransport();
      //$transport->send($message);

      //Setup SMTP transport using PLAIN authentication
      $transport = new SmtpTransport();
      $options = new SmtpOptions(array(
         'name'              => 'gmail',
         'host'              => 'smtp.gmail.com',
         'port'              => '587',
         'connection_class'  => 'plain',
         'connection_config' => array(
            'username' => 'asistencia.uca.edu.py@gmail.com',
            'password' => '7Td&.li1',
            'ssl'      => 'tls',
         ),
      ));
      $transport->setOptions($options);
      $transport->send($message);

      $usuario->password = md5($usuario->password);
      $this->getUsuarioTable()->saveUsuario($usuario);

   }

   public function recoverAction() {
      $usuario = null;
      $request = $this->getRequest();
      if ($request->isPost()) {
         $data = $request->getPost();
         if (!is_null($data['username'])) {

            try {
               $usuario = $this->getUsuarioTable()->getUsuarioByUserName($data['username']);
            } catch(\Exception $ex) {
               $usuario = null;
               $nombre = $data['username'];
               echo "
                  <script language='JavaScript'>
                     alert('Usuario \"$nombre\" NO existe!');
                  </script>
               ";
            }

            if (!is_null($usuario)) {
               try {
                  $this->sendPassword($usuario);
               } catch(Exception $e) {
                  echo "ERROR: NO se puedo enviar el mail!";
                  echo $e->getMessage();
               }
            }
         }
      }

      return array(
         'usuario' => $usuario,
      );

   }

   public function getUsuarioTable() {
      if (!$this->usuarioTable) {
         $sm = $this->getServiceLocator();
         $this->usuarioTable = $sm->get('Usuarios\Model\UsuarioTable');
      }
      return $this->usuarioTable;
   }

}
